// 高亮函数
function highlight(text, keyword) {
  if (!keyword) return text;
  const reg = new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
  return text.replace(reg, match => `<span class=\"highlight\">${match}</span>`);
}

// 渲染搜索结果
function renderResults(groupedData, keyword) {
  const resultDiv = document.getElementById('result');
  resultDiv.innerHTML = '';

  if (!groupedData || Object.keys(groupedData).length === 0) {
    resultDiv.innerHTML = '<div style="color:#888;padding-top: 16px;">未找到相关代码。</div>';
    return;
  }

  Object.entries(groupedData).forEach(([projectName, projectData]) => {
    const projectSection = document.createElement('div');
    projectSection.className = 'project-section';

    // 项目标题
    const projectTitle = document.createElement('div');
    projectTitle.className = 'group-title';
    projectTitle.innerHTML = `<a href="${projectData.projectUrl}" target="_blank">
      ${highlight(projectName, keyword)} <span class="branch">(${projectData.branch})</span>
    </a>`;

    // 文件列表容器
    const filesContainer = document.createElement('div');
    filesContainer.className = 'files-container';

    Object.entries(projectData.files).forEach(([fileName, items]) => {
      const fileSection = document.createElement('div');
      fileSection.className = 'file-section';

      // 文件标题
      const fileTitle = document.createElement('div');
      fileTitle.className = 'subgroup-title';
      const fileUrl = `${projectData.projectUrl.replace('.git', '')}/src/${projectData.branch}/${fileName.replace('..\\..','')}`;
      fileTitle.innerHTML = `<a href="${fileUrl}" target="_blank">
        ${highlight(fileName.split('\\').pop(), keyword)}
      </a>`;

      // 代码行列表
      document.getElementById('searchInput').addEventListener('click', function(e) {
      e.stopPropagation();
      e.preventDefault();
    });

    const codeLines = items.map(item => {
        return `<div class="search-result-item">
          <div class="code-line">
            <span class="line-number">#${item.lineNumber}</span>
            ${highlight(item.codeLine, keyword)}
          </div>
        </div>`;
      }).join('');

      fileSection.appendChild(fileTitle);
      fileSection.insertAdjacentHTML('beforeend', codeLines);
      filesContainer.appendChild(fileSection);
    });

    projectSection.appendChild(projectTitle);
    projectSection.appendChild(filesContainer);
    resultDiv.appendChild(projectSection);
  });
}

// 搜索按钮事件
document.getElementById('searchBtn').onclick = function() {
  const allRepos = JSON.parse(localStorage.getItem('gitReposConfig')) || [];
  if (allRepos.length === 0) {
    return;
  }
  
  // 获取选中的项目
  let repos = getSelectedRepos();
  
  const keyword = document.getElementById('searchInput').value.trim();
  if (!keyword) {
    document.getElementById('result').innerHTML = '<div style="color:#888;padding-top: 16px;">请输入搜索关键字。</div>';
    return;
  }
  
  document.getElementById('searchBtn').disabled = true;
  document.getElementById('searchBtn').innnerText = '搜索中...';
  
  fetch(`/api/search?q=${encodeURIComponent(keyword)}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      q: keyword,
      repos
    })
  })
    .then(res => res.json())
    .then(data => {
      renderResults(data.results, keyword);
    })
    .catch(err => {
      document.getElementById('result').innerHTML = '请求失败: ' + err;
    })
    .finally(() => {
      document.getElementById('searchBtn').disabled = false;
      document.getElementById('searchBtn').innnerText = '搜一下';
    });
};

// 回车快捷搜索
document.getElementById('searchInput').addEventListener('keydown', function(e) {
  if (e.key === 'Enter') document.getElementById('searchBtn').click();
});

// 自定义多选下拉列表功能
const customSelect = document.querySelector('.custom-select');
const selectHeader = customSelect.querySelector('.select-header');
const selectOptions = customSelect.querySelector('.select-options');
const selectedText = customSelect.querySelector('.selected-text');

// 初始化项目下拉列表
function initRepoSelect() {
  const repos = JSON.parse(localStorage.getItem('gitReposConfig')) || [];
  const optionsContainer = customSelect.querySelector('.select-options');
  
  // 清空并重新填充选项
  optionsContainer.innerHTML = '';
  
  // 添加搜索框
  const searchInput = document.createElement('input');
  searchInput.type = 'text';
  searchInput.placeholder = '搜索项目...';
  searchInput.className = 'search-dropdown';
  searchInput.addEventListener('click', function(e) {
    e.stopPropagation();
  });
  searchInput.addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const options = optionsContainer.querySelectorAll('.option');
    
    options.forEach(option => {
      const text = option.textContent.toLowerCase();
      if (text.includes(searchTerm) || option.dataset.value === 'all') {
        option.style.display = 'flex';
      } else {
        option.style.display = 'none';
      }
    });
  });
  optionsContainer.appendChild(searchInput);
  
  // 添加全部项目选项
  const allOption = document.createElement('div');
  allOption.className = 'option selected';
  allOption.dataset.value = 'all';
  allOption.innerHTML = `
    <span class="checkmark"></span>
    全部
  `;
  optionsContainer.appendChild(allOption);
  
  // 添加项目选项
  repos.sort((a, b) => 
    (a.name || a.remoteUrl.split('/').pop().replace('.git', ''))
      .localeCompare(b.name || b.remoteUrl.split('/').pop().replace('.git', ''))
  );
  repos.forEach(repo => {
    const option = document.createElement('div');
    option.className = 'option';
    option.dataset.value = repo.remoteUrl;
    option.innerHTML = `
      <span class="checkmark"></span>
      ${repo.name || repo.remoteUrl.split('/').pop().replace('.git', '')}
    `;
    optionsContainer.appendChild(option);
  });
  
  // 添加选项点击事件
  optionsContainer.querySelectorAll('.option').forEach(option => {
    option.addEventListener('click', function(e) {
      e.stopPropagation();
      
      if (this.dataset.value === 'all') {
        // 处理全部项目选项
        optionsContainer.querySelectorAll('.option').forEach(opt => {
          opt.classList.remove('selected');
        });
        this.classList.add('selected');
      } else {
        // 处理普通项目选项
        const allOption = optionsContainer.querySelector('.option[data-value="all"]');
        allOption.classList.remove('selected');
        this.classList.toggle('selected');
      }
      
      updateSelectedText();
    });
  });
}

// 更新显示的选中文本
function updateSelectedText() {
  const selectedOptions = customSelect.querySelectorAll('.option.selected');
  
  if (selectedOptions.length === 0 || 
      (selectedOptions.length === 1 && selectedOptions[0].dataset.value === 'all')) {
    selectedText.textContent = '全部';
  } else {
    const selectedNames = Array.from(selectedOptions)
      .filter(opt => opt.dataset.value !== 'all')
      .map(opt => opt.textContent.trim());
    
    selectedText.textContent = selectedNames.length > 0 
      ? selectedNames.join(', ') 
      : '全部';
  }
}

// 获取选中的项目值
function getSelectedRepos() {
  const selectedOptions = customSelect.querySelectorAll('.option.selected');
  const allRepos = JSON.parse(localStorage.getItem('gitReposConfig')) || [];
  
  if (selectedOptions.length === 0 || 
      selectedOptions[0].dataset.value === 'all') {
    return allRepos;
  }
  
  return allRepos.filter(repo => 
    Array.from(selectedOptions).some(opt => opt.dataset.value === repo.remoteUrl)
  );
}

// 下拉列表开关
selectHeader.addEventListener('click', function(e) {
  e.stopPropagation();
  customSelect.classList.toggle('open');
});

// 点击外部关闭下拉
document.addEventListener('click', function() {
  customSelect.classList.remove('open');
});

// 初始化
initRepoSelect();

// 监听本地存储变化更新下拉列表
window.addEventListener('storage', (e) => {
  if (e.key === 'gitReposConfig') {
    initRepoSelect();
  }
});

// 默认空结果
document.getElementById('result').innerHTML = '<div style="color:#888;padding-top: 16px;">请输入关键字进行代码搜索。</div>';